#endcoding:utf-8
class OffersController < ApplicationController
  before_action :logged_in?
  layout "user"
  def new
    store_location
    if userinfo.counselor_info.nil?
      flash[:danger] = '完善个人信息后才能报价'
      redirect_to '/editinfo'
    end
    @demand = Demand.find(params[:demand_id])
    if hasOffered?(params[:demand_id])
      flash[:danger] = "已经报过价了"
      redirect_to @demand
    end
    @offer = Offer.new
  end
  def index

  end
  def update
    offer = Offer.find(params[:id])
    ActiveRecord::Base.transaction do
      if  offer.update(:status=>params[:offer][:status])
        demand = Demand.find(params[:offer][:demand_id])
        demand.update(:status=>3)
        message = "咨询师已经确认了订单，他将与您联系"
        content = message_link(message,demand_path(demand))
        send_message(params[:offer][:demand_user_id],content,params[:offer][:demand_id])
        render :json=>{:stat=>1}
      else
        render :json=>{:stat=>0}
      end
    end
  end


  def create
    @demand = Demand.find(params[:offer][:demand_id])
    if hasOffered? params[:offer][:demand_id]
      flash[:info] = "已经报过价了"
      redirect_to @demand
    else
      @offer = Offer.new(offer_params)
      if @offer.save
        flash[:info] = "报价成功"
        user = userinfo
        message = "您的\""+@demand.projects+"\"需求有一个最新报价："+user.name+"报价"+@offer.price.to_s+"元"
        content = message_link message,demand_path(@demand)
        send_message @demand.user_id,content,@demand.id
        redirect_to @demand
      else
        flash[:info] = "报价失败"
        @errors = @offer.errors.full_messages
        render "new"
      end
    end

  end
  def destroy

  end
  private
  def offer_params
    params.require(:offer).permit(:user_id,:demand_id,:price,:description)
  end
end
